const fs       = require('fs');
const log      = require('./log');
const path     = require('path');

class fileUtil{
    constructor() {
    }

    /**
     * 删除目录
     * @param path
     */
    static deleteDir(path){
        let files = [];
        if(fs.existsSync(path)) {
            files = fs.readdirSync(path);
            files.forEach(function (file, index) {
                let curPath = path + "/" + file;
                if (fs.statSync(curPath).isDirectory()) { // recurse
                    fileUtil.deleteDir(curPath);
                } else { // delete file
                    fileUtil.deleteFile(curPath);
                }
            });
            fs.rmdirSync(path);
        }
        log.info(`Delete folder:[${path}].... Successful.`);
    }

    /**
     * 删除文件
     * @param filePath
     */
    static deleteFile(filePath){
        fs.unlinkSync(filePath);
        log.info(`Delete file:${filePath}`);
    }

    /**
     * 批量删除文件
     */
    static deleteFiles(filePaths){
        for(let file of filePaths){
            fileUtil.deleteFile(file);
        }
    }

    /**
     * 写入数据到文件(同步写入)
     * @param data      数据
     * @param filePath 文件路径
     */
    static writeFileAsync (filePath,data) {
        fs.writeFileSync(filePath,data);
    }

    /**
     * 读取路径信息
     * @param {string} path 路径
     */
    static getStat(path){
        return new Promise((resolve, reject) => {
            fs.stat(path, (err, stats) => {
                if(err){
                    resolve(false);
                }else{
                    resolve(stats);
                }
            })
        })
    }

    /**
     * 创建路径
     * @param {string} dir 路径
     */
    static mkdir(dir){
        return new Promise((resolve, reject) => {
            fs.mkdir(dir, err => {
                if(err){
                    resolve(false);
                }else{
                    resolve(true);
                }
            })
        })
    }

    /**
     * 路径是否存在，不存在则创建
     * @param {string} dir 路径
     */
    static async dirExists(dir){
        let isExists = await fileUtil.getStat(dir);
        //如果该路径且不是文件，返回true
        if(isExists && isExists.isDirectory()){
            return true;
        }else if(isExists){     //如果该路径存在但是文件，返回false
            return false;
        }
        //如果该路径不存在
        let tempDir = path.parse(dir).dir;      //拿到上级路径
        //递归判断，如果上级目录也不存在，则会代码会在此处继续循环执行，直到目录存在
        let status = await fileUtil.dirExists(tempDir);
        let mkdirStatus;
        if(status){
            mkdirStatus = await fileUtil.mkdir(dir);
        }
        return mkdirStatus;
    }

    /**
     * 判断文件是否存在
     * @returns {Promise<boolean>}
     */
    static async exists(path){
        return fs.existsSync(path);
    }

    /**
     * 读取文件
     * @returns {Promise<string>}
     */
    static async readFile(path){
        if(!path || !await fileUtil.exists(path)){
            throw new Error(`Not found folder or file:${path}`);
        }
        return fs.readFileSync(path,'utf8');
    }

    /**
     * 读取文件夹下所有文件名称
     */
    static async readDirFiles(dirPath){
        return new Promise(async (resolve, reject) => {
            let jsonFiles = [];
            function findJsonFile(dirPath){
                let files = fs.readdirSync(dirPath);
                files.forEach(function (item, index) {
                    let fPath = path.join(dirPath,item);
                    let stat = fs.statSync(fPath);
                    if(stat.isDirectory() === true) {
                        findJsonFile(fPath);
                    }
                    if (stat.isFile() === true) {
                        jsonFiles.push(fPath);
                    }
                });
            }
            findJsonFile(dirPath);
            resolve(jsonFiles)
        })
    }

    static async readDirFileContent(dirPath){
        return new Promise(async (resolve, reject) => {
            let files = await fileUtil.readDirFiles(dirPath);
            if(!files || files.length === 0){
                reject([]);
                return;
            }
            let contents = [];
            for(let p of files){
                let content = await fileUtil.readFile(p);
                contents.push(content);
            }
            resolve(contents);
        })
    }

    /**
     *  用于判断路径是否存在， 如果不存在，则创建一个
     */
    static async dirExists(dir){
        let isExists = await fileUtil.getStat(dir);
        //如果该路径且不是文件，返回true
        if(isExists && isExists.isDirectory()){
            return true;
        }else if(isExists){     //如果该路径存在但是文件，返回false
            return false;
        }
        //如果该路径不存在
        let tempDir = path.parse(dir).dir;      //拿到上级路径
        //递归判断，如果上级目录也不存在，则会代码会在此处继续循环执行，直到目录存在
        let status = await fileUtil.dirExists(tempDir);
        let mkdirStatus;
        if(status){
            mkdirStatus = await fileUtil.mkdir(dir);
        }
        return mkdirStatus;
    }



    static async isFileExisted(path_way){
        return new Promise((resolve, reject) => {
            fs.access(path_way, (err) => {
                if (err) {
                    resolve(false);
                } else {
                    resolve(true);
                }
            })
        })
    }
}

module.exports = fileUtil;
